package com.atung.merchant.config.security;

import com.alibaba.fastjson.JSONObject;
import com.atung.merchant.dto.AuthUserEntity;
import com.atung.merchant.result.ApiResult;
import com.atung.merchant.service.AuthSecurityService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author wangbo
 * @since 2022/10/17 14:36
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private AuthSecurityService authSecurityService;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private FlowConfiguration flowConfiguration;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("X-Farm-Token");

        String requestURI = request.getRequestURI();
        if (!flowConfiguration.currentLimiting(WebIpUtil.getIpAddress(request), requestURI)) {
            response.setStatus(200);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(JSONObject.toJSONString(ApiResult.requestControl()));
            return;

        }
        //验证当前ip 是是否合法
        if (StringUtils.hasText(token)) {
            // 验证token的有效性，并提取用户名
            String username = jwtTokenUtil.getUsernameFromToken(token);
            Boolean tokenIp = jwtTokenUtil.isTokenIp(token, WebIpUtil.getIpAddress(request));
            if (!tokenIp) {
                filterChain.doFilter(request, response);
                return;
            }
            if (username != null) {
                // 检查SecurityContextHolder中是否已经有认证信息
                if (SecurityContextHolder.getContext().getAuthentication() == null) {
                    AuthUserEntity authUserEntity = authSecurityService.loadUserByUsername(username);
                    if (authUserEntity != null) {
                        UsernamePasswordAuthenticationToken authenticationToken =
                                new UsernamePasswordAuthenticationToken(authUserEntity, null, authUserEntity.getAuthorities());
                        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        // 将认证信息设置到SecurityContextHolder
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
